// 获取应用实例
const app = getApp();

Page({
  data: {
    userPoints: null,
    availableRewards: [],
    loading: false
  },

  onLoad() {
    this.loadRewardCenterData();
  },

  /**
   * 加载奖励中心数据
   */
  async loadRewardCenterData() {
    this.setData({ loading: true });
    
    try {
      // 从全局数据获取奖励中心数据
      const rewardCenterData = app.globalData.rewardCenterData;
      if (rewardCenterData) {
        this.setData({
          userPoints: rewardCenterData.userPoints,
          availableRewards: rewardCenterData.availableRewards || []
        });
      } else {
        // 如果没有全局数据，直接调用API
        const rewardAPI = require('~/api/reward');
        const result = await rewardAPI.getRewardCenter();
        if (result.code === 200) {
          this.setData({
            userPoints: result.data.userPoints,
            availableRewards: result.data.availableRewards || []
          });
        } else {
          throw new Error(result.message || '获取奖励中心数据失败');
        }
      }
    } catch (error) {
      console.error('加载奖励中心数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 兑换奖励
   */
  async redeemReward(e) {
    const { reward } = e.currentTarget.dataset;
    
    if (!reward.canRedeem) {
      wx.showToast({
        title: '积分不足',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '确认兑换',
      content: `确定要花费 ${reward.pointsCost} 积分兑换 ${reward.name} 吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            const rewardAPI = require('~/api/reward');
            const result = await rewardAPI.redeemReward(reward.rewardId);
            
            if (result.code === 200) {
              wx.showToast({
                title: '兑换成功',
                icon: 'success'
              });
              // 重新加载数据
              this.loadRewardCenterData();
            } else {
              wx.showToast({
                title: result.message || '兑换失败',
                icon: 'error'
              });
            }
          } catch (error) {
            console.error('兑换奖励失败:', error);
            wx.showToast({
              title: '兑换失败',
              icon: 'error'
            });
          }
        }
      }
    });
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadRewardCenterData().then(() => {
      wx.stopPullDownRefresh();
    });
  }
});
